//
//  ChangeReceiptCardViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/13.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "ChangeReceiptCardViewController.h"
#import "ChangeReceiptTableViewCell.h"
#import "ChangeReceiptTableFootterView.h"

#import "BankListView.h"
#import "BankListModelPack.h"
#import "ChangeReceiptCardModelPack.h"
#import "RSA.h"
#import "BankListTableViewCell.h"

#import <UIImageView+WebCache.h>


@interface ChangeReceiptCardViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *InfoArray;
@property(nonatomic,strong)ChangeReceiptTableFootterView *cv;


//弹出银行名称
@property(nonatomic,strong)BankListView *bv;
//银行名称模型数组
@property(nonatomic,strong)NSMutableArray *bankNameArray;

//替代Cell的tf
@property(nonatomic,strong)UITextField *holdCardNameTf;
@property(nonatomic,strong)UITextField *bankPhoneTf;
@property(nonatomic,strong)UITextField *bankCardTf;
@property(nonatomic,strong)UITextField *banNameTf;

/**
 键盘上方的完成
 */
@property(nonatomic,strong)UIToolbar *toolbar;


@end

@implementation ChangeReceiptCardViewController

-(NSMutableArray *)bankNameArray
{
    if (_bankNameArray == nil) {
        _bankNameArray = [NSMutableArray array];
    }
    return _bankNameArray;
}

-(NSMutableArray *)InfoArray
{
    if (_InfoArray == nil) {
        _InfoArray = [NSMutableArray array];
    }
    return _InfoArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改收款卡";
    self.view.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    //创建tableView
    [self createTableView];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

#pragma mark  键盘回收
-(void)keyboardHide:(NSNotification *)note
{
    self.tableView.contentInset = UIEdgeInsetsZero;
}
#pragma mark  键盘弹出
-(void)keyboardShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.contentInset= UIEdgeInsetsMake(0,0, keyBoardRect.size.height,0);
}


-(void)createTableView
{
    self.InfoArray = @[@"持卡人姓名",@"预留手机号",@"银行卡号",@"银行名称"].mutableCopy;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, ETScreenH - 64 - 10) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = YES;
    self.tableView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:244 / 255.0 blue:246 / 255.0 alpha:1];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[ChangeReceiptTableViewCell class] forCellReuseIdentifier:@"cell"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.InfoArray.count;
    }else
    {
        return self.bankNameArray.count;
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        ChangeReceiptTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.tipsValueTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLab.text = self.InfoArray[indexPath.row];
        if (indexPath.row == 1) {
            cell.tipsValueTf.text = self.bankPhoneNumStr;
            cell.tipsValueTf.keyboardType = UIKeyboardTypeNumberPad;
            cell.tipsValueTf.inputAccessoryView = [self addToolbar];
            self.bankPhoneTf = cell.tipsValueTf;
        }
        if (indexPath.row == 2) {
            cell.tipsValueTf.text = self.bankCardNumStr;
            cell.tipsValueTf.keyboardType = UIKeyboardTypeNumberPad;
            cell.tipsValueTf.inputAccessoryView = [self addToolbar];
            self.bankCardTf = cell.tipsValueTf;
            self.bankCardTf.delegate = self;
        }
        if (indexPath.row == 3) {
            cell.tipsValueTf.text = self.bankNameStr;
            self.banNameTf = cell.tipsValueTf;
        }
        
        //持卡人姓名赋值,且不能点击
        if (indexPath.row == 0) {
            self.holdCardNameTf = cell.tipsValueTf;
            cell.tipsValueTf.text = [AppTools shareInstance].userInfo.userName;
            cell.tipsValueTf.userInteractionEnabled = NO;
        }else
        {
            cell.tipsValueTf.userInteractionEnabled = YES;
        }
        
        //最后一个cell不显示分割线  且点击显示银行列表
        if (indexPath.row == self.InfoArray.count - 1) {
            cell.lineView.hidden = YES;
            cell.arrowImv.hidden = NO;
            cell.tipsValueTf.userInteractionEnabled = NO;
        }else
        {
            cell.arrowImv.hidden = YES;
        }
        return cell;
    }else
    {
        BankListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bankListCell" forIndexPath:indexPath];
        BankListRecord *record = self.bankNameArray[indexPath.row];
        [cell.iconImv sd_setImageWithURL:[NSURL URLWithString:record.bankIcon] placeholderImage:[UIImage imageNamed:@"logo_yinhang"]];
        cell.titleLab.text = record.text;
        
        return cell;
    }
}

-(void)textFieldDidChange :(UITextField *)textField{
    
    //CVN2码只能输入3位
    if (textField == self.bankPhoneTf) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}


//数字键盘加完成按钮
- (UIToolbar *)addToolbar
{
    self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 40)];
    self.toolbar.backgroundColor = ETColorWithRGB(232, 232, 232);
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.backgroundColor = [UIColor whiteColor];
    [btn setTitle:@"完成" forState:(UIControlStateNormal)];
    [btn setTitleColor:ETColorWithRGB(0, 0, 0) forState:(UIControlStateNormal)];
    btn.layer.borderColor = ETColorWithRGB(0, 0, 0).CGColor;
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = 4;
    btn.frame = CGRectMake(0, 0, 76, 28);
    [btn addTarget:self action:@selector(textFieldDone) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.toolbar.items = @[space, bar];
    return self.toolbar;
}
-(void)textFieldDone
{
    [self.view endEditing:YES];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        if (indexPath.row == self.InfoArray.count - 1) {
            NSLog(@"点击获取银行");
            self.tableView.userInteractionEnabled = NO;
            //退键盘
            [self.bankPhoneTf resignFirstResponder];
            [self.bankCardTf resignFirstResponder];
            [self getBankListWithCardNum:@""];

        }
    }else
    {
        BankListRecord *record = self.bankNameArray[indexPath.row];
        self.banNameTf.text = record.text;
        self.bankCodeStr = record.value;
        self.bankNameStr = record.text;
        [self BankListViewdismiss];
        
    }
    
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    //当银行卡号失去焦点时,请求后端的银行
    if (textField == self.bankCardTf && textField.text.length != 0) {
        [self getBankListWithCardNum:self.bankCardTf.text];
    }
}

-(void)getBankListWithCardNum:(NSString *)cardNum
{
    
    if (cardNum.length != 0) {
        [self NoTipsNetWithCardNum:cardNum];
    }else
    {
        [self TipsNetWithCardNum];
    }
    
}

//无提示框请求银行列表
-(void)NoTipsNetWithCardNum:(NSString *)cardNum
{
    BankListRequest *request = [[BankListRequest alloc] init];
    request.cardNo = cardNum;
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/bankCard/getBankByCardNo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOSTNOTips:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dealbankListWithResponse:responseObject];
            });
        }else
        {
            self.banNameTf.text = @"";
            self.tableView.userInteractionEnabled = YES;
        }
    } FailedHandler:^(NSError *error) {
        
        self.tableView.userInteractionEnabled = YES;
        
    }];
}
//有提示框请求银行列表
-(void)TipsNetWithCardNum
{
    BankListRequest *request = [[BankListRequest alloc] init];
    request.cardNo = @"";
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/bankCard/getBankByCardNo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dealbankListWithResponse:responseObject];
            });
        }else
        {
            self.banNameTf.text = @"";
            self.tableView.userInteractionEnabled = YES;
        }
    } FailedHandler:^(NSError *error) {
        
        self.tableView.userInteractionEnabled = YES;
        
    }];
}


-(void)dealbankListWithResponse:(id )responseObject
{
    BankListResponse *bankListResponse = [BankListResponse mj_objectWithKeyValues:responseObject];
    NSLog(@"%@",bankListResponse);
    
    if (bankListResponse.response.bankList.count == 1) {
        //输入框赋值
        BankListRecord *record = bankListResponse.response.bankList[0];
        self.banNameTf.text = record.text;
        self.bankCodeStr = record.value;
    }else
    {
        [self popBanList];
        
        
        [self.bv.offBtn addTarget:self action:@selector(offBtnAction) forControlEvents:(UIControlEventTouchDown)];
        [self.bankNameArray removeAllObjects];
        for (BankListRecord *record in bankListResponse.response.bankList) {
            //存储到数组,点击时直接取数据
            [self.bankNameArray addObject:record];
        }
        [self.bv.bankListTableView reloadData];
        NSLog(@"%@",self.bankNameArray);
    }
}
-(void)offBtnAction
{
    [self BankListViewdismiss];
}

-(void)popBanList
{
    self.bv = [[BankListView alloc] initWithFrame:(CGRectMake(0, ETScreenH, ETScreenW, 400))];
    AppDelegate *delegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:self.bv];
    
    
    //给弹出框加上点击事件  响应底部弹窗消失
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesturedDetected:)];
    tapGesture.delegate = self;
    [self.bv addGestureRecognizer:tapGesture];
    
    
    
    
    __weak ChangeReceiptCardViewController *weakSelf = self;
    self.bv.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [UIView animateWithDuration:0.5 animations:^{
        [weakSelf.bv setFrame:CGRectMake(0, 0, ETScreenW, ETScreenH)];
    } completion:^(BOOL finished) {
        self.tableView.userInteractionEnabled = YES;
        weakSelf.bv.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    }];
    
    self.bv.bankListTableView.delegate = self;
    self.bv.bankListTableView.dataSource = self;
    self.bv.bankListTableView.userInteractionEnabled = YES;
    self.bv.bankListTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    self.bv.bankListTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ETScreenW, 0.0001f)];
    [self.bv.bankListTableView registerClass:[BankListTableViewCell class] forCellReuseIdentifier:@"bankListCell"];
    
}

-(void)tapGesturedDetected:(UIGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self.bv];
    
    if (point.y < ETScreenH - 400) {
        self.bv.backgroundColor = [UIColor clearColor];
        __weak BankListView *weakSelf = self.bv;
        [UIView animateWithDuration:0.5 animations:^{
            weakSelf.frame = CGRectMake(0, ETScreenH, ETScreenW, ETScreenH);
        } completion:^(BOOL finished) {
            
        }];
    }
}

-(void)BankListViewdismiss
{
    self.bv.backgroundColor = [UIColor clearColor];
    __weak BankListView *weakSelf = self.bv;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.frame = CGRectMake(0, ETScreenH, ETScreenW, ETScreenH);
    } completion:^(BOOL finished) {
        
    }];
}




-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return 100.0f;
    }else
    {
        return 0.01f;
    }
    
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        self.cv = [[ChangeReceiptTableFootterView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
        [self.cv.confirmBtn addTarget:self action:@selector(confirmBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
        return self.cv;
    }else
    {
        return nil;
    }
    
}
-(void)confirmBtnAction
{
    NSLog(@"点击确认修改");
    //退键盘
//    [self textFieldDone];
    
    if ([self.bankPhoneTf.text containsString:@"*"]) {
        [self showFailedResultTips:@"请填写正确的手机号" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    if ([self.bankCardTf.text containsString:@"*"]) {
        [self showFailedResultTips:@"请填写正确的银行卡号" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    
    
    ChangeReceiptCardRequest *request = [[ChangeReceiptCardRequest alloc] init];
    request.ID = self.commMercIdStr;
    request.accountName = self.holdCardNameTf.text;
    request.openBankName = self.bankNameStr;
    request.bankLeaveMobile = [RSA encryptString:self.bankPhoneTf.text publicKey:ETPublicKeyStr];
    request.accountNo = [RSA encryptString:self.bankCardTf.text publicKey:ETPublicKeyStr];
    request.bankCode = self.bankCodeStr;
    NSDictionary *dic = [request mj_keyValues];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/user/changeBrokerInfo"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealChangeReceiptCard];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}

-(void)dealChangeReceiptCard
{
    //修改收款卡成功
    
    //修改成功后回调,改变银行卡片颜色和名字
    if (self.changeReceiptCardBlock) {
        self.changeReceiptCardBlock();
    }
    
    
    [self showSuccessResultTips:@"修改收款卡成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF completionBlock:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
}



-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(nonnull UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    return YES;
}


-(void)dealloc
{
    [self.bv removeFromSuperview ];
    [self.toolbar removeFromSuperview];
}


@end
